package cn.itcast.controller;


import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Member;
import cn.itcast.service.MemberService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/member")
@CrossOrigin
public class MemberController {

    @Reference
    private MemberService memberService;


    /**
     * 所有会员分页列表查询
     */
    @GetMapping("/findPage")
    public Result findPage(QueryPageBean queryPageBean){

        try {
            PageResult pageResult = memberService.pageQuery(queryPageBean);

            return new Result(true, MessageConstant.QUERY_MEMBER_SUCCESS,pageResult);
        } catch (Exception e) {
            e.printStackTrace();

            return new Result(false,MessageConstant.QUERY_MEMBER_FAIL);
        }



    }

    /**
     * 新增会员档案
     */
    @PostMapping("/add")
    //将前端传递过来的参数封装到member对象中
    public Result saveMember(@RequestBody Member member){

        try {

           member.setBirthday(new Date());
            member.setStatus(1);
            memberService.add(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
    }


    @GetMapping("/{id}")
    public Result findById(@PathVariable int id){

        try {
            Member member = memberService.findById(id);
            return new Result(true, MessageConstant.QUERY_MEMBER_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MEMBER_FAIL);
        }

    }



    /**
     * 编辑会员档案
     */
    @PutMapping("/update")
    public Result edit(@RequestBody Member member){
        try {
            memberService.edit(member);
            return new Result(true, MessageConstant.UPDATE_MEMBER_STATUS_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.UPDATE_MEMBER_STATUS_FAIL);
        }
    }




    /**
     * 查询所有会员档案
     *
     * @return
     */
    @GetMapping(path = "/findAll")
    public Result findAll() {
        try {
            List<Member> memberList = memberService.findAll();
            return new Result(true, MessageConstant.QUERY_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MEMBER_FAIL);
        }

    }

    /**
     * 测试
     */
    public void test(){

    }


}
